<template>
  <div class="common-layout">
    <el-form class="header" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="书名" prop="ipaddr">
        <el-select style="width: 120px" clearable v-model="queryParams.book" placeholder="书名">
          <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
        </el-select>
      </el-form-item>

      <el-form-item label="单元名称" prop="ipaddr">
        <el-select style="width: 120px" clearable v-model="queryParams.unit" placeholder="单元名称">
          <el-option v-for="item in 5" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
        </el-select>
      </el-form-item>

      <el-form-item label="测试">
        <el-select style="width: 160px" clearable v-model="queryParams.times" placeholder="测试范围">
          <el-option
              v-for="dict in word_test_scope"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学生姓名">
        <el-input style="width: 120px" clearable v-model="queryParams.userName" placeholder="学生姓名"></el-input>
      </el-form-item>

      <el-form-item label="校区">
        <el-input style="width: 120px" clearable v-model="queryParams.userSchool"
                  placeholder="请输入校区名称"></el-input>
      </el-form-item>

      <el-form-item label="类型">
        <el-select style="width: 140px" clearable v-model="queryParams.type" placeholder="请选择">
          <el-option
              v-for="dict in studyTypeList"
              :key="dict.type"
              :label="dict.label"
              :value="dict.type"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleRecordData">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="border: solid 1px;margin: 10px 10px">
      <el-row :gutter="20" style="padding: 20px 20px">
        <el-col :span="6">
          <el-table :data="todayData" max-height="200" border>
            <el-table-column label="统计名称" width="240" align="center" prop="name"/>
            <el-table-column label="值"  align="center" prop="value"/>
          </el-table>
        </el-col>

        <el-col :span="6">
          <el-table :data="groupListData" max-height="200" border>
            <el-table-column label="日期" width="120" align="center" prop="date"/>
            <el-table-column label="总人次"  align="center" prop="count"/>
          </el-table>
        </el-col>

        <el-col :span="6">
          <el-table :data="groupStudentData" max-height="200" border>
            <el-table-column label="日期" width="120" align="center" prop="date"/>
            <el-table-column label="校区" width="80" align="center" prop="school"/>
            <el-table-column label="学生" width="80" align="center" prop="name"/>
            <el-table-column label="次数"  align="center" prop="count"/>
          </el-table>
        </el-col>

        <el-col :span="6">
          <el-table :data="groupSchoolData" max-height="200" border>
            <el-table-column label="日期" width="120" align="center" prop="date"/>
            <el-table-column label="校区" width="80" align="center" prop="name"/>
            <el-table-column label="次数"  align="center" prop="count"/>
          </el-table>
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="20">
      <el-col :sm="24" :lg="24" style="padding: 0 20px">
        <el-table :data="wordTestList" border>
          <el-table-column width="120" label="书名" align="center" prop="book" >
            <template #default="scope">
              <span v-if="scope.row.book === null">---</span>
              <span>{{scope.row.book}}</span>
            </template>
          </el-table-column>
          <el-table-column width="120" label="单元" align="center" prop="unit" >
            <template #default="scope">
              <span v-if="scope.row.unit === null">---</span>
              <span>{{scope.row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column label="组号" width="80" align="center" prop="group" >
            <template #default="scope">
              <span v-if="scope.row.unit !== null">---</span>
              <span v-else>{{scope.row.group}}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型"
                           align="center"
                           :formatter="formatType"
                           prop="type" >
          </el-table-column>
          <el-table-column label="校区" width="100" align="center" prop="userSchool"/>
          <el-table-column label="学生" align="center" prop="userName"/>
          <el-table-column label="测试" width="80" align="center" prop="times">
            <template #default="scope">
              <dict-tag :options="word_test_scope" :value="scope.row.times"/>
            </template>
          </el-table-column>
          <el-table-column label="正确个数" width="80" align="center" prop="correctNum"/>
          <el-table-column label="测试总数" width="80" align="center" prop="wordNum"/>
          <el-table-column label="测试时间" width="180" align="center" prop="createTime"/>
          <el-table-column label="正确率" align="center" prop="correctRate">
            <template #default="scope">
              <span>{{ parseInt(scope.row.correctRate * 100).toFixed(0) }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="用时" align="center" prop="usedTime"/>
          <el-table-column label="详情" align="center" width="80" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link @click="getDetails(scope.row)" type="primary">查看</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <div class="pagination-actions">
            <el-button @click="getStatisticMore(null)" type="primary">
             更多统计
            </el-button>
          </div>
          <pagination
              style="margin-right: 5px"
              v-show="size > 0"
              :total="size"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="handleRecordData"
          />
        </div>
      </el-col>
    </el-row>

    <el-dialog style="padding: 20px" title="测试记录详情" v-model="testResultWindow" width="900px" append-to-body>
      <el-row type="flex" justify="center">
        <el-text style="font-size: 18px;color: rebeccapurple">
          测试总数:{{ testTotalNum }}---完成个数{{
            testCompleteNum
          }}---正确个数:{{ correctNum }}---完成率:{{
            parseInt(testCompleteRate)
          }}%---正确率:{{ parseInt(testCorrectRate) }}%
        </el-text>
      </el-row>
      <el-table :data="testCompleteData">
        <el-table-column width="120" label="书名" align="center" prop="book" >
          <template #default="scope">
            <span v-if="scope.row.book === null">---</span>
            <span>{{scope.row.book}}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" label="单元" align="center" prop="unit" >
          <template #default="scope">
            <span v-if="scope.row.unit === null">---</span>
            <span>{{scope.row.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="组号" width="80" align="center" prop="group" >
          <template #default="scope">
            <span v-if="scope.row.unit !== null">---</span>
            <span v-else>{{scope.row.group}}</span>
          </template>
        </el-table-column>
        <el-table-column label="单词/词组" align="center" prop="name"/>
        <el-table-column v-if="false" label="词组" align="center" prop="options"/>
        <el-table-column label="词性" width="60" align="center" prop="type"/>
        <el-table-column label="汉语" align="center" prop="chinese"/>
        <el-table-column label="测试结果" width="100" align="center" prop="result">
          <template #default="scope">
            <dict-tag :options="word_test_status" :value="scope.row.result"/>
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="记录时间" width="180" align="center" prop="time"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {getCurrentInstance} from 'vue';
import {studyTypeList, groupWordBySchool, groupWordTest, listWordTest, statisticsData} from "@/api/word/wordRecord.js";
import useUserStore from '@/store/modules/user'
import {listTestRecordDetailByUser} from "@/api/word/index.js";
import {parseTime} from "@/utils/ruoyi";
import {getStatisticMore} from "@/api/teach/route.js";

const {proxy} = getCurrentInstance();
const {word_test_scope} = proxy.useDict("word_test_scope")
const {word_test_status} = proxy.useDict("word_test_status")
// 弹窗
let correctNum = ref(0)
let testTotal = ref(0)
let testTotalNum = ref(0)
let testCompleteNum = ref(0)
let testCompleteData = ref([])
let todayData = ref([])
let groupListData = ref([])
let groupCountData = ref([])
let groupSchoolData = ref([])
let groupStudentData = ref([])
let testCompleteRate = ref(0)
let testCorrectRate = ref(0)
let testResultWindow = ref(false)

let wordTestList = ref([])
let size = ref(0)

let queryParams = ref({
  unit: undefined,
  book: undefined,
  type: undefined,
  pageNum: 1,
  times: undefined,
  userId: useUserStore().id,
  pageSize: 10
})

let queryStatistics = ref({
  date: parseTime(new Date(), '{y}-{m}-{d}'),
  userId: useUserStore().id,
})

let statistics = ref({
  todayNumAll: 0,
  todayNum: 0,
  todayRateAll: 0,
  todayRate: 0
})

initPage()

function initPage() {

  listWordTest(queryParams.value).then(res => {
    if (res.code === 200) {
      wordTestList.value = res.rows;
      // console.log(res)
      size.value = res.total;
    }
  })
  getStatisticsData()
}

// 格式化函数：根据 typeList 转换 type 值
function formatType(row, column, cellValue) {
  // 从 typeList 中找到匹配的项（cellValue 即当前行的 type 值）
  // console.log(cellValue)
  const matched = studyTypeList.find(item => item.type === cellValue);
  // 找到则返回 label，否则返回原始值或默认文本
  return matched ? matched.label : '未知类型';
}

function getStatisticsData() {
  statisticsData(queryStatistics.value).then(res => {
    // console.log(res);
    if (res.code === 200) {
      statistics.value = res.data
    }
    todayData.value = []
    todayData.value.push({
          'name': '今日完成测试人次(全部)',
          'value': statistics.value.todayNumAll
        }, {
          'name': '今日完成测试人次(本校区)',
          'value': statistics.value.todayNum
        }, {
          'name': '今日测试人数平均正确率(全部)',
          'value': statistics.value.todayRateAll
        }, {
          'name': '今日测试人数平均正确率(本校区)',
          'value': statistics.value.todayRate
        }
    )
  })
  // let school = queryParams.value.userSchool;
  // if (school === undefined) {
  //   school = ''
  // }
  // console.log(school)
  groupWordTest().then(res => {
    // console.log(res)
    if (res.code === 200) {
      groupListData.value = res.data.all
      groupSchoolData.value = res.data.bySchool
      groupStudentData.value = res.data.byStudent
    }
  })
}

function getDetails(row) {
  // console.log(row)
  if (row.practice === undefined || row.practice === null) {
    proxy.$modal.msgWarning("此记录详情未开放")
    return
  }
  let query = {
    practice: row.practice,
    userId: row.userId,
    way: row.way,
    type: row.type
  }
  if (row.group !== undefined && row.group !== null && row.group !== 0) {
    query.way = 4
  }
  // console.log(query)
  testCorrectRate.value = parseInt(row.correctRate * 100)
  correctNum.value = row.correctNum
  testTotalNum.value = row.wordNum
  testCompleteNum.value = row.complete
  testCompleteRate.value = parseInt(row.complete) / parseInt(row.wordNum) * 100
  listTestRecordDetailByUser(query).then(res => {
    // console.log(res)
    if (res.code === 200) {
      if (res.data === undefined || res.data === null || res.data.length === 0) {
        proxy.$modal.msgWarning("此记录详情已被删除或未查询到数据")
        return
      }
      // console.log(res)
      testResultWindow.value = true
      testCompleteData.value = res.data
      testTotal.value = res.data.length
    }
  })
}

//连接MYSQL数据库-查询全部
function handleRecordData() {
  let userName = queryParams.value.userName;
  let userSchool = queryParams.value.userSchool;
  let name = userName === undefined ? '无' : userName
  let school = userSchool === undefined ? '无' : userSchool

  let bookName = queryParams.value.book;
  let book = bookName === undefined ? '无' : bookName
  let unitName = queryParams.value.unit;
  let unit = unitName === undefined ? '无' : unitName

  let type = queryParams.value.type;
  let typeName = '无'
  if (type !== undefined) {
    typeName = studyTypeList.find(item =>
        item.type === type
    )
    typeName = typeName.label
  }

  let times = queryParams.value.times;
  // console.log(times)
  let timeName = '无'
  if (times !== undefined && times !== null) {
    timeName = word_test_scope.value.find(item => item.value === times)
    timeName = timeName.label
  }

  proxy.$modal.msg("查询的书名:" + book + "  课程:" + unit
      + "  用户:" + name + "  校区:" + school + ' 类型:' + typeName + ' 测试范围:' + timeName)

  listWordTest(queryParams.value).then(res => {
    if (res.code === 200) {
      wordTestList.value = res.rows;
      // console.log(res)
      size.value = res.total;
    }
  })

  //新增加入筛选后两个表格的功能
  if (school !== '无') {
    groupWordBySchool(school).then(res => {
      if (res.code === 200) {
        groupSchoolData.value = res.data.bySchool
        groupStudentData.value = res.data.byStudent
      }
    })
  }
}

function resetQuery() {
  queryParams.value.book = ''
  queryParams.value.unit = ''
  queryParams.value.times = null
  queryParams.value.type = undefined
  queryParams.value.userName = undefined
  queryParams.value.userSchool = undefined
  handleRecordData()
  getStatisticsData()
}

</script>

<style scoped lang="scss">
.clickAfter:focus {
  outline: none;
  color: darkred;
}

.statistic-small :deep(.el-statistic__prefix) {
  font-size: 14px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 5px;
  display: flex;
  justify-content: space-between;  /* 左右布局 */
  align-items: center;             /* 垂直居中 */
  padding: 0;
}

/* 左侧按钮区域 */
.pagination-actions {
  display: flex;
  gap: 8px;  /* 按钮之间的间距 */
}

.header {
  margin-top: 20px;
  margin-left: 20px;
}
</style>
